/**
 * 新增、修改保养计划
 */

import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import moment from 'moment';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';

import {
    Card,
    Form,
    Typography,
    Row,
    Col,
    Select,
    Input,
    InputNumber,
    DatePicker,
    Radio,
    TreeSelect,
    Button,
    Table,
    Modal,
    message,
    Spin,
} from 'antd';

import { get, post } from '../../axios/http';
import { formatTime, BasicTable } from '../../utils/x.js';

const { Title } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;


function parseTreeData(arr) {
    const result = [];
    for (const i in arr) {
        const a = {
            title: arr[i].name,
            value: arr[i].id,
        };
        if (arr[i].children && arr[i].children.length > 0) {
            a.children = parseTreeData(arr[i].children);
        }
        result.push(a);
    }
    return result;
}

/**
 * 主表单 - 保养部位 - 新增明细 - 编辑表单
 */
const MaintenanceProgramDetailForm1Table6Form1 = React.forwardRef(function MaintenanceProgramDetailForm1Table6Form1({ form, form: { getFieldDecorator } }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    return (
        <Form>
            <Form.Item label="保养部位">
                {getFieldDecorator('equMaintainPart', {
                    rules: [
                        {
                            required: true,
                        }
                    ]
                })(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="保养标准">
                {getFieldDecorator('equMaintainStandard', {
                    rules: [
                        {
                            required: true,
                        }
                    ]
                })(
                    <Input />
                )}
            </Form.Item>
            {getFieldDecorator('id')(
                <Input type="hidden" />
            )}
        </Form>
    );
});

/**
 * 主表单 - 保养部位 - 新增明细表格
 */
function MaintenanceProgramDetailForm1Table6({ onEvent }) {
    const [data, setData] = useState([]);
    const [treeData, setTreeData] = useState([]);
    const [equType, setEquType] = useState(null);
    const [modalData, setModalData] = useState({});
    const [modalDataIndex, setModalDataIndex] = useState(-1);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const handleAddClick = useCallback(() => {
        setData(prev => {
            return [
                ...prev,
                {
                    equMaintainPart: '',
                    equMaintainStandard: '',
                }
            ];
        });
    }, []);

    const handleActionClick = useCallback((e) => {
        e.preventDefault();
        const action = e.currentTarget.getAttribute('data-action');
        const index = Number(e.currentTarget.getAttribute('data-index'));
        switch (action) {
            case 'edit': {
                setModalDataIndex(index);
                setModalData(JSON.parse(e.currentTarget.getAttribute('data-data')));
                setIsModalOpen(true);
                break;
            }
            case 'delete': {
                setData(prev => {
                    const newData = [...prev];
                    newData.splice(index, 1);
                    return newData;
                });
                break;
            }
        }
    }, []);

    const form1Ref = useRef();
    const Form1Table6Form1Wrap = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            return {
                id: Form.createFormField({ value: data.id }),
                equMaintainPart: Form.createFormField({ value: data.equMaintainPart }),
                equMaintainStandard: Form.createFormField({ value: data.equMaintainStandard }),
            };
        }
    })(MaintenanceProgramDetailForm1Table6Form1);

    const handleModalOk = useCallback(() => {
        form1Ref.current.form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            setData(prev => {
                const newData = [...prev];
                newData.splice(modalDataIndex, 1, values);
                return newData;
            });
            setIsModalOpen(false);
        });
    }, [modalDataIndex]);
    const handleModalCancel = useCallback(() => {
        setIsModalOpen(false);
    }, []);

    const handleTree1Change = useCallback((value, label) => {
        setEquType({ value, title: label[0] });
    }, []);

    const tableColumns = [
        {
            title: '保养部位',
            dataIndex: 'equMaintainPart',
        },
        {
            title: '保养标准',
            dataIndex: 'equMaintainStandard',
        },
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-action="edit" data-index={index} data-data={JSON.stringify(row)} style={{ marginRight: 10 }} onClick={handleActionClick}>编辑</a>
                        <a href="#" data-action="delete" data-index={index} onClick={handleActionClick}>删除</a>
                    </>
                );
            },
        },
    ];

    useEffect(() => {
        (async () => {
            const res = await get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList');
            res && setTreeData(parseTreeData(res.data));
        })();
    }, []);

    useEffect(() => {
        onEvent({ type: 'UPDATE_SELECTED', data });
    }, [data, onEvent]);

    useEffect(() => {
        onEvent({ type: 'UPDATE_TYPE', data: equType });
    }, [equType, onEvent])

    return (
        <>
            <div style={{ marginBottom: 10 }}>
                <Button type="primary" icon="plus" onClick={handleAddClick}>添加明细</Button>
                <span style={{ marginLeft: 10 }}>设备类别：</span>
                <TreeSelect style={{ minWidth: 150 }} treeData={treeData} onChange={handleTree1Change} />
            </div>
            <Table size="small" rowKey={(row, index) => index} dataSource={data} columns={tableColumns} pagination={false} />
            <Modal title="编辑部位" visible={isModalOpen} onOk={handleModalOk} onCancel={handleModalCancel}>
                <Form1Table6Form1Wrap wrappedComponentRef={form1Ref} data={modalData} />
            </Modal>
        </>
    );
}

/**
 * 工单表单 - 保养负责人 - 搜索表单
 */
function MaintenanceProgramDetailForm1Table5SearchForm({ form, form: { getFieldDecorator }, onSubmit, treeData3 }) {
    const [treeData1, setTreeData1] = useState([]);

    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const emptyItem = { title: '全部', value: null };

    useEffect(() => {
        const parseDepData = (arr) => {
            const result = [];
            for (const item of arr) {
                result.push({
                    value: item.id,
                    title: item.name,
                    children: parseDepData(item.children),
                });
            }
            return result;
        };

        (async () => {
            try {
                // const res = await get(lotAuth + '/department/queryTreeDepartment');
                const res = await get(lotAuth2 + '/department/queryTreeDepartment');
                setTreeData1(parseDepData(res.data));
            } catch (err) {}
        })();
    }, []);

    return (
        <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 10 }}>
            <Form.Item label="用户名称">
                {getFieldDecorator('userName')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="执行班组">
                {getFieldDecorator('team')(
                    <TreeSelect treeData={[emptyItem, ...treeData3]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item label="使用部门">
                {getFieldDecorator('department')(
                    <TreeSelect treeData={[emptyItem, ...treeData1]} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 主表单 - 保养负责人 - 选择人员表格
 */
function MaintenanceProgramDetailForm1Table5({ selectedKeys, onSelectChange, treeData3 }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [pagination, setPagination] = useState({});

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'userName',
        },
        {
            title: '部门',
            dataIndex: 'department',
        },
        {
            title: '职务',
            dataIndex: 'roleName',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const SearchFormWrap = useMemo(() => {
        return Form.create()(MaintenanceProgramDetailForm1Table5SearchForm);
    }, [treeData3]);

    const handleSearchFormSubmit = useCallback((values) => {
        fetchData(values, true);
    }, []);

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findUserOfMaintain', { params: dataQuery });
                res && setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <SearchFormWrap onSubmit={handleSearchFormSubmit} treeData3={treeData3} />
            <BasicTable
                rowKey="id"
                dataSource={data}
                columns={tableColumns}
                rowSelection={tableRowSelection}
                loading={isDataLoading}
                pagination={pagination} />
        </>
    );
}

/**
 * 主表单 - 保养部位表格
 */
function MaintenanceProgramDetailForm1Table4({ data, onEvent }) {
    const handleDeleteClick = useCallback((e) => {
        e.preventDefault();
        const index = Number(e.currentTarget.getAttribute('data-index'));
        onEvent({ type: 'DELETE_ITEM', index });
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-index={index} onClick={handleDeleteClick}>删除</a>
                    </>
                );
            },
        },
        {
            title: '保养部位',
            dataIndex: 'equMaintainPart',
        },
        {
            title: '保养标准',
            dataIndex: 'equMaintainStandard',
        },
    ];

    return (
        <BasicTable dataSource={data} columns={tableColumns} />
    );
}


/**
 * 主表单 - 保养部位 - 选择表格
 */
function MaintenanceProgramDetailForm1Table3({ selectedKeys, onSelectChange }) {
    const [data, setData] = useState([]);
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [pagination, setPagination] = useState({});

    const tableColumns = [
        {
            title: '设备类型',
            dataIndex: 'equType',
        },
        {
            title: '保养部位',
            dataIndex: 'equMaintainPart',
        },
        {
            title: '保养标准',
            dataIndex: 'equMaintainStandard',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findMaintainPositionDetails', { params: dataQuery });
                res && setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <BasicTable
            rowKey="id"
            dataSource={data}
            columns={tableColumns}
            rowSelection={tableRowSelection}
            loading={isDataLoading}
            pagination={pagination} />
    );
}

/**
 * 主表单 - 设备信息 - 选择设备 - 搜索表单
 */
function MaintenanceProgramDetailForm1Table2SearchForm({ form, form: { getFieldDecorator }, onSubmit }) {
    const [treeData1, setTreeData1] = useState([]); // 设备类型
    const [treeData2, setTreeData2] = useState([]); // 所在部门

    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const treeData1Extra = [
        {
            title: '全部',
            value: null,
        },
        ...treeData1,
    ];
    const treeData2Extra = [
        {
            title: '全部',
            value: null,
        },
        ...treeData2,
    ];

    useEffect(() => {
        const parseDepData = (arr) => {
            const result = [];
            for (const item of arr) {
                result.push({
                    value: item.id,
                    title: item.name,
                    children: parseDepData(item.children),
                });
            }
            return result;
        };

        (async () => {
            try {
                const res1 = await get(euqApplicationName + '/currency/queryEquipmentType');
                setTreeData1(res1.data.map(item => {
                    return {
                        value: item.id,
                        title: item.name,
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                // const res2 = await get(lotAuth + '/department/queryTreeDepartment');
                const res2 = await get(lotAuth2 + '/department/queryTreeDepartment');
                setTreeData2(parseDepData(res2.data));
            } catch (err) {}
        })();
    }, []);

    return (
        <Form layout="inline" onSubmit={handleSubmit} style={{ marginBottom: 10 }}>
            <Form.Item label="搜索条件">
                {getFieldDecorator('quickSearch')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item label="设备类型">
                {getFieldDecorator('equTypeId')(
                    <TreeSelect treeData={treeData1Extra} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item label="使用部门">
                {getFieldDecorator('depId')(
                    <TreeSelect treeData={treeData2Extra} style={{ width: 120 }} />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 主表单 - 设备信息 - 选择设备表格
 */
function MaintenanceProgramDetailForm1Table2({ selectedKeys, onSelectChange }) {
    const [data, setData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [dataQuery, setDataQuery] = useState({});
    const [pagination, setPagination] = useState({});

    const tableColumns = [
        {
            title: '设备编号',
            dataIndex: 'equCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equName',
        },
        {
            title: '规格型号',
            dataIndex: 'equSpecsModel',
        },
        {
            title: '设备类型',
            dataIndex: 'equTypeName',
        },
        {
            title: '使用部门',
            dataIndex: 'department',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
    };

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const SearchFormWrap = useMemo(() => {
        return Form.create()(MaintenanceProgramDetailForm1Table2SearchForm);
    }, []);

    const handleSearchFormSubmit = useCallback((values) => {
        const newValue = { ...values };
        if (newValue.quickSearch === '') {
            delete newValue.quickSearch;
        }
        fetchData(newValue, true);
    }, []);

    useEffect(() => {
        (async () => {
            setIsLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintain/findEquipment', { params: dataQuery });
                setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <SearchFormWrap onSubmit={handleSearchFormSubmit} />
            <BasicTable
                rowKey="id"
                dataSource={data}
                loading={isLoading}
                columns={tableColumns}
                rowSelection={tableRowSelection}
                pagination={pagination} />
        </>
    );
}

/**
 * 主表单 - 设备信息表格
 */
function MaintenanceProgramDetailForm1Table1({ data, onEvent }) {
    const handleDeleteClick = useCallback((e) => {
        e.preventDefault();
        const index = Number(e.currentTarget.getAttribute('data-index'));
        onEvent({ type: 'DELETE_ITEM', index });
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <a href="#" data-index={index} onClick={handleDeleteClick}>删除</a>
                );
            },
        },
        {
            title: '设备编号',
            dataIndex: 'equCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equName',
        },
        {
            title: '规格型号',
            dataIndex: 'equSpecsModel',
        },
        {
            title: '设备类型',
            dataIndex: 'equTypeName',
        },
        {
            title: '使用部门',
            dataIndex: 'department',
        },
    ];

    return (
        <BasicTable rowKey="id" dataSource={data} columns={tableColumns} />
    );
}

/**
 * 主表单
 */
const MaintenanceProgramDetailForm1 = React.forwardRef(function MaintenanceProgramDetailForm1({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue }, mode, onEvent }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    const [init, setInit] = useState(false);

    const treeData1 = ['日', '月'].map(text => ({
        title: text,
        value: text,
        key: text,
    })); // 循环周期单位
    const [treeData2, setTreeData2] = useState([]); // 保养负责人
    const [treeData3, setTreeData3] = useState([]); // 保养班组
    const [treeData4, setTreeData4] = useState([]); // 保养级别

    const [isModal1Open, setIsModal1Open] = useState(false);
    const [selected1, setSelected1] = useState({ key: [], row: [] });

    const [isModal2Open, setIsModal2Open] = useState(false);
    const [selected2, setSelected2] = useState({ key: [], row: [] });

    const [isModal3Open, setIsModal3Open] = useState(false);
    const [selected3, setSelected3] = useState({ key: [], row: [] });

    const [isModal4Open, setIsModal4Open] = useState(false);
    const [selected4, setSelected4] = useState([]);
    const [selected4Type, setSelected4Type] = useState({});

    const [equipmentInfoList, setEquipmentInfoList] = useState([]);
    const [equipmentRequirement, setEquipmentRequirement] = useState([]);

    const treeData2Wrap = useMemo(() => {
        return treeData2.map(item => (
            <Option key={item.value} value={item.value}>{item.title}</Option>
        ));
    }, [treeData2]);

    // 设备信息表格
    const handleTable1Event = useCallback((e) => {
        switch (e.type) {
            case 'DELETE_ITEM': {
                setEquipmentInfoList(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
        }
    }, []);

    // 设备信息窗口
    const handleModal1Ok = useCallback(() => {
        setEquipmentInfoList(prev => {
            const newData = [...prev];
            const ids = newData.map(item => item.id);
            selected1.row.forEach(item => {
                ids.indexOf(item.id) === -1 && newData.push({ ...item });
            });
            return newData;
        });
        setIsModal1Open(false);
    }, [selected1]);
    const handleModal1Cancel = useCallback(() => {
        setIsModal1Open(false);
    }, []);
    const handleSelectEquipmentClick = useCallback(() => {
        setIsModal1Open(true);
    }, []);

    // 设备信息窗口 - 表格
    const handleTable2SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected1({ key: selectedRowKeys, row: selectedRows });
    }, []);

    // 保养部位窗口
    const handleModal2Ok = useCallback(() => {
        setEquipmentRequirement(prev => {
            const newData = [...prev];
            const ids = newData.map(item => item.requirementId);
            selected2.row.forEach(item => {
                ids.indexOf(item.requirementId) === -1 && newData.push({ ...item });
            });
            return newData;
        });
        setIsModal2Open(false);
    }, [selected2]);
    const handleModal2Cancel = useCallback(() => {
        setIsModal2Open(false);
    }, []);
    const handleSelectPositionClick = useCallback(() => {
        setIsModal2Open(true);
    }, []);
    const handleAddPositionClick = useCallback(() => {
        setIsModal4Open(true);
    }, []);

    // 保养部位窗口 - 表格
    const handleTable3SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected2({ key: selectedRowKeys, row: selectedRows });
    }, []);

    // 保养部位表格
    const handleTable4Event = useCallback((e) => {
        switch (e.type) {
            case 'DELETE_ITEM': {
                setEquipmentRequirement(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
        }
    }, []);

    // 选择人员窗口
    const handleModal3Ok = useCallback(() => {
        setTreeData2(prev => {
            const newData = [...prev];
            const newIds = [];
            const ids = newData.map(item => item.value);
            selected3.row.forEach(item => {
                if (ids.indexOf(item.id) === -1) {
                    newData.push({
                        title: item.userName,
                        value: item.id,
                        key: item.id,
                    });
                    newIds.push(item.id);
                }
            });
            const ls = [...getFieldValue('maintainPersonId')];
            Array.prototype.push.apply(ls, selected3.key);
            const ls2 = [...new Set(ls)];
            setFieldsValue({
                maintainPersonId: ls2,
            });
            return newData;
        });
        setIsModal3Open(false);
    }, [selected3]);
    const handleModal3Cancel = useCallback(() => {
        setIsModal3Open(false);
    }, []);
    const handleSelectPersonClick = useCallback(() => {
        setIsModal3Open(true);
    }, []);

    // 选择人员窗口 - 表格
    const handleTable5SelectChange = useCallback((selectedRowKeys, selectedRows) => {
        setSelected3({ key: selectedRowKeys, row: selectedRows });
    }, []);

    // 保养部位 - 新增明细窗口
    const handleModal4Ok = useCallback(() => {
        let validated = true;
        selected4.forEach(item => {
            if (item.equMaintainPart.length === 0) {
                validated = false;
                return;
            }
            if (item.equMaintainStandard.length === 0) {
                validated = false;
                return;
            }
        });
        if (!validated) {
            message.error('表单验证未通过');
            return;
        }
        (async () => {
            try {
                const userId = Number(localStorage.getItem('userId'));
                const equTypeId = (selected4Type && selected4Type.value) ? selected4Type.value : null;
                const equType = (selected4Type && selected4Type.title) ? selected4Type.title : null;
                const reqData = selected4.map(item => ({
                    equMaintainPart: item.equMaintainPart,
                    equMaintainStandard: item.equMaintainStandard,
                    equTypeId,
                    userId,
                }));
                // console.log(reqData, selected4, selected4Type); return;
                const res = await post(euqApplicationName + '/equipmentMaintainPlan/addEquipmentRequirement', { data: reqData }, true);
                setEquipmentRequirement(prev => {
                    const newData = [...prev];
                    reqData.forEach((item, index) => {
                        newData.push({
                            id: res.data[index],
                            requirementId: res.data[index],
                            equTypeId,
                            equType,
                            equMaintainPart: item.equMaintainPart,
                            equMaintainStandard: item.equMaintainStandard,
                        });
                    });
                    return newData;
                });
                message.info('部位添加成功');
                setIsModal4Open(false);
            } catch (err) {console.log(err);}
        })();
    }, [selected4, selected4Type]);
    const handleModal4Cancel = useCallback(() => {
        setIsModal4Open(false);
    }, []);

    const handleTable6Event = useCallback((e) => {
        switch (e.type) {
            case 'UPDATE_SELECTED':
                setSelected4(e.data);
                break;
            case 'UPDATE_TYPE':
                setSelected4Type(e.data);
                break;
        }
    }, []);

    // 其它
    const handleDisabledDate = useCallback((current) => {
        return current && current < moment().startOf('day');
    }, []);

    const handleSubmitClick = useCallback((e) => {
        form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            // "loopCycleUnit", "loopCycle",
            if(values.loopStyle===0){
                values.loopCycleUnit = '月'
                values.loopCycle = 1000
                onEvent && onEvent({ type: 'FORM_SUBMIT', value: values });
            }else{
                onEvent && onEvent({ type: 'FORM_SUBMIT', value: values });
            }
        });
    }, [onEvent]);
    const handleCancelClick = useCallback(() => {
        onEvent && onEvent({ type: 'FORM_CANCEL' });
    }, [onEvent]);

    useEffect(() => {
        init && setFieldsValue({
            maintainPersonList: treeData2,
        });
    }, [init, treeData2]);

    useEffect(() => {
        init && setFieldsValue({
            equipmentInfoList: JSON.stringify(equipmentInfoList),
        });
    }, [init, equipmentInfoList]);

    useEffect(() => {
        init && setFieldsValue({
            equipmentRequirement: JSON.stringify(equipmentRequirement),
        });
    }, [init, equipmentRequirement]);

    useEffect(() => {
        // console.log('init', form.getFieldsValue());
        const initEquipmentRequirement = getFieldValue('equipmentRequirement');
        setTreeData2(getFieldValue('maintainPersonList'));
        setEquipmentRequirement(initEquipmentRequirement ? JSON.parse(initEquipmentRequirement) : []);

        (async () => {
            try {
                const res3 = await get(euqApplicationName + '/currency/queryTeam');
                res3 && setTreeData3(res3.data.map(item => {
                    return {
                        title: item.name,
                        value: item.id,
                        key: item.id,
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res4 = await get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=6');
                res4 && setTreeData4(res4.data.map(item => {
                    return {
                        title: item.configValue.trim(),
                        value: item.id,
                        key: item.id,
                    };
                }));
            } catch (err) {}
        })();
        setInit(true);
    }, []);

    return (
        <>
            <Form layout="horizontal" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <div hidden={mode !== 'edit'}>
                    <Title level={4}>设备信息</Title>
                    <Row>
                        <Col span={6}>
                            <Form.Item label="设备编号">
                                {getFieldDecorator("equipmentCode")(
                                    <Input disabled />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item label="设备名称">
                                {getFieldDecorator("equipmentName")(
                                    <Input disabled />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item label="规格型号">
                                {getFieldDecorator("specsModel")(
                                    <Input disabled />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item label="设备类别">
                                {getFieldDecorator("typeName")(
                                    <Input disabled />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item label="使用部门">
                                {getFieldDecorator("equipmentDepart")(
                                    <Input disabled />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                </div>

                <Title level={4}>保养信息</Title>
                <Row>
                    <Col span={6}>
                        <Form.Item label="保养班组">
                            {getFieldDecorator("maintainTeamId")(
                                <TreeSelect treeData={treeData3} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养级别">
                            {getFieldDecorator("maintainLevel")(
                                <TreeSelect treeData={treeData4} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={22} style={{ paddingRight: 10 }}>
                        <Form.Item label="保养负责人" labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
                            {getFieldDecorator("maintainPersonId", {
                                initialValue: [],
                                rules: [
                                    {
                                        validator: (rule, value, callback) => {
                                            if (value.length < 1) {
                                                callback('必须选择至少一个保养负责人');
                                            }
                                            callback();
                                        },
                                    }
                                ],
                            })(
                                <Select mode="multiple" readonly>
                                    {treeData2Wrap}
                                </Select>
                            )}
                        </Form.Item>
                        {getFieldDecorator("maintainPersonList", {
                            initialValue: [],
                        })(
                            <Input type="hidden" />
                        )}
                    </Col>
                    <Col span={2}>
                        <Button type="primary" block style={{ marginTop: 4 }} onClick={handleSelectPersonClick}>选择人员</Button>
                    </Col>
                    <Col span={6} style={{ display: 'none' }}>
                        <Form.Item label="提醒时间">
                            {getFieldDecorator("reminderTime")(
                                <Input placeholder="默认单位为天" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="计划时间">
                            {getFieldDecorator("jxbysj", {
                                rules: [
                                    {
                                        required: true,
                                        message: '必须选择保养时间',
                                    }
                                ]
                            })(
                                <RangePicker /*disabledDate={handleDisabledDate}*/ />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="循环方式">
                            {getFieldDecorator("loopStyle", {
                                initialValue: 1,
                            })(
                                <Radio.Group>
                                    <Radio value={0}>单次</Radio>
                                    <Radio value={1}>多次</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item label="循环周期" labelCol={{ span: 12 }} wrapperCol={{ span: 12 }}>
                            {getFieldDecorator("loopCycle", {
                                rules: [
                                    {
                                        validator: (rule, value, callback) => {
                                            const loopStyle = getFieldValue('loopStyle');
                                            if (loopStyle === 1 && !value) {
                                                callback('选择多次循环时，本项必填');
                                                return;
                                            }
                                            callback();
                                        },
                                    }
                                ]
                            })(
                                <InputNumber style={{ width: '100%' }} disabled={getFieldValue('loopStyle')===0?true:false}/>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={2}>
                        <Form.Item>
                            {getFieldDecorator("loopCycleUnit", {
                                initialValue: '日',
                            })(
                                <TreeSelect treeData={treeData1}  disabled={getFieldValue('loopStyle')===0?true:false}/>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label="计划描述" labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
                            {getFieldDecorator("description")(
                                <TextArea rows={4} />
                            )}
                        </Form.Item>
                    </Col>
                </Row>

                <div hidden={mode === 'edit'}>
                    <Title level={4} style={{ marginTop: 10 }}>设备信息</Title>
                    <div>
                        <Button icon="select" type="primary" onClick={handleSelectEquipmentClick}>选择设备</Button>
                    </div>
                    <MaintenanceProgramDetailForm1Table1 data={equipmentInfoList} onEvent={handleTable1Event} />
                    {getFieldDecorator("equipmentInfoList")(
                        <Input type="hidden" />
                    )}
                </div>

                <Title level={4} style={{ marginTop: 10 }}>保养部位</Title>
                <div>
                    <Button icon="select" type="primary" style={{ marginRight: 5 }} disabled={mode === 'edit'} onClick={handleSelectPositionClick}>选择明细</Button>
                    <Button icon="plus" type="primary" disabled={mode === 'edit'} onClick={handleAddPositionClick}>新增明细</Button>
                </div>
                <MaintenanceProgramDetailForm1Table4 data={equipmentRequirement} onEvent={handleTable4Event} />
                {getFieldDecorator("equipmentRequirement")(
                    <Input type="hidden" />
                )}

                {getFieldDecorator("id")(
                    <Input type="hidden" />
                )}

                <div style={{ marginTop: 20 }}>
                    <Button type="primary" style={{ marginRight: 5 }} onClick={handleSubmitClick}>保存</Button>
                    <Button onClick={handleCancelClick}>取消</Button>
                </div>
            </Form>

            <Modal title="选择设备" width={880} visible={isModal1Open} onOk={handleModal1Ok} onCancel={handleModal1Cancel}>
                <MaintenanceProgramDetailForm1Table2 selectedKeys={selected1.key} onSelectChange={handleTable2SelectChange} />
            </Modal>
            <Modal title="选择明细" width={640} visible={isModal2Open} onOk={handleModal2Ok} onCancel={handleModal2Cancel}>
                <MaintenanceProgramDetailForm1Table3 selectedKeys={selected2.key} onSelectChange={handleTable3SelectChange} />
            </Modal>
            <Modal title="选择人员" width={880} visible={isModal3Open} onOk={handleModal3Ok} onCancel={handleModal3Cancel}>
                <MaintenanceProgramDetailForm1Table5 selectedKeys={selected3.key} onSelectChange={handleTable5SelectChange} treeData3={treeData3} />
            </Modal>
            <Modal title="新增保养明细" visible={isModal4Open} onOk={handleModal4Ok} onCancel={handleModal4Cancel}>
                <MaintenanceProgramDetailForm1Table6 onEvent={handleTable6Event} />
            </Modal>
        </>
    );
});

/**
 * 主组件
 */
function MaintenanceProgramDetail() {
    const { id } = useParams();
    const history = useHistory();

    const [mode, setMode] = useState('add');
    const [isDataLoading, setIsDataLoading] = useState(true);
    const [formData, setFormData] = useState({});

    const viewTitle = {
        add: '新增计划',
        edit: '计划明细',
    };

    const handleForm1Event = useCallback((e) => {
        switch (e.type) {
            case 'FORM_SUBMIT': {
                const reqData = {
                    ...e.value,
                    maintainStartTime: formatTime(e.value.jxbysj[0]),
                    maintainEndTime: formatTime(e.value.jxbysj[1]),
                    equipmentInfoList: JSON.parse(e.value.equipmentInfoList).map(item => item.id),
                    equipmentRequirement: JSON.parse(e.value.equipmentRequirement).map(item => ({
                        requirementId: item.requirementId,
                    })),
                    maintainPersonId: e.value.maintainPersonId.join(','),
                    maintainPersonName: e.value.maintainPersonId.map(id => {
                        return e.value.maintainPersonList.filter(item => item.value === id)[0].title;
                    }).join(','),
                    userId: Number(localStorage.getItem('userId')),
                };
                delete reqData.jxbysj;
                delete reqData.maintainPersonList;
                // console.log('submit:', reqData); return;
                (async () => {
                    try {
                        const res = await post(euqApplicationName + '/equipmentMaintainPlan/saveEquipmentMaintainPlan', { data: reqData });
                        message.info('计划保存成功');
                        history.replace('/MaintenanceProgram');
                    } catch (err) {}
                })();
                break;
            }
            case 'FORM_CANCEL': {
                history.goBack();
                break;
            }
        }
    }, []);

    const form1Ref = useRef();

    const Form1 = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            // console.log('edit:', data); return;
            const personId = data.maintainPersonId ? data.maintainPersonId.split(',').map(Number) : [];
            const personName = data.maintainPerson ? data.maintainPerson.split(',') : [];
            const personList = personId.map((id, index) => ({
                title: personName[index],
                value: id,
                key: id,
            }));
            const equipmentRequirement = data.equipmentMaintainPositionVOList ? data.equipmentMaintainPositionVOList.map(item => ({
                id: item.id,
                requirementId: item.requirementId,
                equMaintainPart: item.positionName,
                equMaintainStandard: item.maintainStandard,
            })) : [];
            return (data && data.id) ? {
                id: Form.createFormField({ value: data.id }),
                equipmentCode: Form.createFormField({ value: data.equipmentCode }),
                equipmentName: Form.createFormField({ value: data.equipmentName }),
                specsModel: Form.createFormField({ value: data.specsModel }),
                typeName: Form.createFormField({ value: data.typeName }),
                equipmentDepart: Form.createFormField({ value: data.equipmentDepart }),
                maintainTeamId: Form.createFormField({ value: data.maintainTeamId }),
                maintainLevel: Form.createFormField({ value: data.maintainLevelId }),
                maintainPersonId: Form.createFormField({ value: personId }),
                maintainPersonList: Form.createFormField({ value: personList }),
                reminderTime: Form.createFormField({ value: data.reminderTime }),
                jxbysj: Form.createFormField({ value: [
                    moment(data.maintainStartTime),
                    moment(data.maintainEndTime),
                ] }),
                loopStyle: Form.createFormField({ value: data.loopStyle }),
                loopCycle: Form.createFormField({ value: data.loopCycle }),
                loopCycleUnit: Form.createFormField({ value: data.loopCycleUnit }),
                description: Form.createFormField({ value: data.description }),
                equipmentInfoList: Form.createFormField({ value: [] }),
                equipmentRequirement: Form.createFormField({ value: JSON.stringify(equipmentRequirement) }),
            } : {}
        }
    })(MaintenanceProgramDetailForm1);

    useEffect(() => {
        if (id) {
            setMode('edit');
            (async () => {
                try {
                    const res = await get(euqApplicationName + '/equipmentMaintainPlan/findEquipmentMaintainPlan', { params: { id } });
                    if (res && res.data.length > 0) {
                        setFormData(res.data[0]);
                        setIsDataLoading(false);
                    } else {
                        Modal.error({
                            title: '未找到保养计划',
                            onOk() {
                                history.back();
                            },
                        });
                    }
                } catch (err) {}
            })();
        } else {
            setIsDataLoading(false);
        }
    }, []);

    return (
        <>
            <h3>{viewTitle[mode]}</h3>
            <Card size="small" style={{ position: 'relative' }}>
                <Form1 wrappedComponentRef={form1Ref} data={formData} mode={mode} onEvent={handleForm1Event} />
                {isDataLoading && (
                    <div className="x-cover-loading2">
                        <Spin size="large" />
                    </div>
                )}
            </Card>
        </>
    );
}

export default MaintenanceProgramDetail;
